//
//  WebSocketManager.m
//  DJIVideo
//
//  Created by wenpd on 2021/4/8.
//

#import "WebSocketManager.h"

@interface WebSocketManager()

@property (strong, nonatomic) SRWebSocket* websocket;
@property (assign, nonatomic) BOOL isOpened;

@end

@implementation WebSocketManager

+ (instancetype)shareManager{
    static dispatch_once_t once_token;
    static WebSocketManager* instance;
    dispatch_once(&once_token, ^{
        instance = [[WebSocketManager alloc]init];
    });
    return instance;
}

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message{
    NSLog(@"SRWebSocket ReceiveMessage:%@", message);
}

- (void)webSocketDidOpen:(SRWebSocket *)webSocket{
    self.websocket = webSocket;
    self.isOpened = true;
}

- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error{
    NSLog(@"SRWebSocket error:%@", error.description);
}

- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean{
    self.isOpened = false;
    self.websocket = nil;
}

- (void)openWebsocket:(NSString *)url param:(NSDictionary*)param{
    if(!self.websocket || !self.isOpened){
        [NSCharacterSet URLQueryAllowedCharacterSet];
        self.websocket = [[SRWebSocket alloc]initWithURL:[NSURL URLWithString:[self obtainUrlWithParam:url param:param]]];
        self.websocket.delegate = self;
        [self.websocket open];
    } else {
        NSLog(@"An opened websocket exist!");
    }
}

- (void)closeWebSocket{
    [self.websocket closeWithCode:1000 reason:@"app close"];
}

- (void)sendData:(NSData *)data{
    if(self.websocket && self.isOpened) {
        [self.websocket send:data];
    }
}

- (NSString*)obtainUrlWithParam:(NSString *)url param:(NSDictionary*)param{
    if(!param || [param count] == 0){
        return url;
    }
    __block NSMutableString *conStr = [NSMutableString string];
    [conStr appendString:@"http://localhost/start?"];
    [param enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [conStr appendFormat:@"%@=%@&", key, obj];
    }];
    [conStr deleteCharactersInRange:NSMakeRange(conStr.length-1, 1)];
    NSLog(@"conStr:%@", conStr);
    NSString* resStr =  [conStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    resStr = [resStr stringByReplacingOccurrencesOfString:@"http://localhost/start" withString:url];
    NSLog(@"websocket url=%@", resStr);
    
    return resStr;
}
@end
